﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;

namespace McgsHttp
{
    internal class httpServer
    {
        public delegate void event_post(string devid, string state, string datetime);
        public delegate string event_get(string devid);
        public event event_post http_post;
        public event event_get http_get; 

        string url = "http://192.168.3.80:18080/";
        HttpListener server = new HttpListener();


        public httpServer()
        {
            server = new HttpListener();
            server.Prefixes.Add(url);
            server.Start();
            Console.WriteLine("Server started at " + url);
         
        }
        public void HttpStart()
        {
            try
            {
                Task.Run(() =>
                {
                    while (true)
                    {
                        HttpListenerContext context = server.GetContext();
                        HttpListenerRequest request = context.Request;
                        string urlabs = request.Url.AbsoluteUri;
                        if (request.HttpMethod == "POST")
                        {
                            post_state(request, context);
                        }
                        if (request.HttpMethod == "GET")
                        {
                            get_args(request,context);
                        }
                    }
                });
            }
            catch (System.Net.HttpListenerException e)
            {
                Console.WriteLine("HttpListenerException: " + e.Message);
                return;
            }
        }
        /// <summary>
        /// 处理POST请求，推送设备状态
        /// </summary>
        /// <param name="request"></param>
        private void post_state(HttpListenerRequest request, HttpListenerContext context)
        {
            string requstpath = "/api/";
            string reppath = request.Url.AbsolutePath;
            if (requstpath != reppath)
            {
                return;
            }
            string requestBody = new StreamReader(request.InputStream, request.ContentEncoding).ReadToEnd();
               
            // 解析请求体
            dynamic requestData = Newtonsoft.Json.JsonConvert.DeserializeObject(requestBody);
            if(http_post != null)
            {
                string devid = requestData.deviceid;
                int state = requestData.state;
                string time = requestData.datetime;
                http_post(devid, state.ToString(), time);
            }
            // 处理请求
            string responseCode = "200";
            string responseMsg = "请求成功";

            // 构建响应体
            string responseBody = Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                code = responseCode,
                msg = responseMsg
            });

            // 发送响应
            byte[] buffer = Encoding.UTF8.GetBytes(responseBody);
            HttpListenerResponse response = context.Response;
            response.ContentLength64 = buffer.Length;
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();
            
        }
        /// <summary>
        /// 处理GET请求，获取参数
        /// </summary>
        /// <param name="request"></param>
        private void  get_args(HttpListenerRequest request, HttpListenerContext context)
        {
            string requstpath = "/api/";
             string reppath = request.Url.AbsolutePath;
            if (requstpath != reppath)
            {
                return;
            }
            string requestBody = new StreamReader(request.InputStream, request.ContentEncoding).ReadToEnd();

            // 解析请求体
            dynamic requestData = Newtonsoft.Json.JsonConvert.DeserializeObject(requestBody);
          
            string responseArg = http_get("");
            // 处理请求
            string responseCode = "200";
            string responseMsg = "请求成功";
            

            // 构建响应体
            string responseBody = Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                code = responseCode,
                msg = responseMsg,
                arg = responseArg
            });

            // 发送响应
            byte[] buffer = Encoding.UTF8.GetBytes(responseBody);
            HttpListenerResponse response = context.Response;
            response.ContentLength64 = buffer.Length;
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
    }
}
